package com.flexoop.lib.components.arraycollection {

	import flash.events.Event;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
 
	public class DeDupeArrayCollection extends ArrayCollection {
		
		public static const DEDUPE_PROPERTY_CHANGED:String	= "dedupePropertyChanged";

		private var _dedupeProperty:String = "";

		[Bindable(event="dedupePropertyChanged")]
		public function get dedupeProperty():String {
			return this._dedupeProperty;
		}

		public function set dedupeProperty( value:String ):void {
			if ( this._dedupeProperty !== value ) {
				this._dedupeProperty = value;
				this.dispatchEvent( new Event( DeDupeArrayCollection.DEDUPE_PROPERTY_CHANGED ) );
			}
		}
		
		private var _originalSource:Array;
 
		/**
		 * 
		 * Needed to override the standard dataprovider in order to reset
		 * the duplicate value each time
		 * 
		 */
		override public function set source( value:Array ):void {
			var _returnArray:Array = value;
 
			if ( value && dedupeProperty.length > 0 ) {
				var _map:Dictionary = new Dictionary( true );
 
				value.forEach( function( item:*, index:int, array:Array ):void {
					_map[ item[ this ] ] = item; // in the loop, this == dedupeProperty
				}, dedupeProperty );
 
				_returnArray = [];
				for each ( var object:Object in _map ) {
					_returnArray.push( object );
				}
			}
 
			super.source = _returnArray;
		}
 
		public function DeDupeArrayCollection( source:Array=null ) {
			this._originalSource = source;
			super( source );
			this.addEventListener( DeDupeArrayCollection.DEDUPE_PROPERTY_CHANGED, handleDedupePropertyChanged );
		}
		
		private function handleDedupePropertyChanged( event:Event ):void {
			this.source = this._originalSource;
		}
 
	}
}